import 'package:dio/dio.dart';
import 'package:kq_flutter_core_widget/network/response.dart';

import 'http.dart';

class FilePreviewHttp {
  static Http http = Http.withDefault(
      baseUrl: "https://www.gomake.cn/highnet/",
      interceptors: [LoggerInterceptorsWrapper()]);

  static ApiResponse<T> _mapperResponse<T>(Map<String, dynamic> mapData) {
    ApiResponse<T> response = ApiResponse.fromJson(mapData, (json) => json,);
    // code转换
    var status = mapData['statusCode'] ?? '';
    response.code = status == '200' ? '1' : '0';
    // msg转换
    response.msg = mapData['message'] ?? '';
    return response;
  }

  /// 获取Wps文件预览链接
  ///
  /// [url] 文件链接
  /// [fileName] 文件名称
  static Future<String?> getWpsUrl(String url, String fileName) async {
    var response = await http.post(
      'framework/base/attachmentManage/previewUrl',
      data: {'fileName': fileName, 'fileUrl': url},
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      responseMapper: _mapperResponse,
    );
    if (response.code == ApiResponse.success) {
      var data = response.data;
      return data['url'];
    }
    return null;
  }

  /// 下载文件
  static Future<String?> downloadFile(String url, String savePath,
      String fileName, ProgressCallback progressCallback,
      {CancelToken? cancelToken}) async {
    var response = await http.download(url, savePath + fileName,
        progressCallback: progressCallback, cancelToken: cancelToken);
    if (response.statusCode == 200) {
      return savePath + fileName;
    }
    return null;
  }
}
